/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package controllers;

import binding.orders.OrderType;
import binding.orders.Orders;
import core.DBEntities;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.transform.Source;
import org.xml.sax.SAXException;
import utils.DefaultErrorHandler;
import utils.UpdateValidate;
import utils.XmlUtils;

public class OrderController extends HttpServlet {

    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, SAXException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        try {
            String webPath = getServletContext().getRealPath("/");
            String xsdPath = webPath + "WEB-INF/classes/schemas/orders.xsd";
            String filePath = webPath + "WEB-INF/XmlDoc/Orders.xml";
            String xslPath = webPath + "WEB-INF/XslDoc/Order.xsl";
            String action = request.getParameter("action");
            if (action.equals("ORDER_UPDATE")) {
                String orderid = request.getParameter("orderid");
                String status = request.getParameter("status");

                DefaultErrorHandler handler = new DefaultErrorHandler();
                UpdateValidate validator = UpdateValidate.Instance(filePath, xsdPath);

                LinkedHashMap<String, String> keys = new LinkedHashMap<String, String>();
                keys.put("Id", orderid);

                LinkedHashMap<String, String> pros = new LinkedHashMap<String, String>();
                pros.put("Status", status);

                Source source = validator.updateOnValidateSource(handler, "Order", keys, pros);

                if (handler.isError()) {
                    String order = "<?xml version='1.0' encoding='UTF-8'?>";
                    order += "<error>" + handler.getErrorMessage() + "</error>";
                    response.setContentType("text/xml");
                    out.write(order);
                } else {
                    Object orderObj = XmlUtils.unMarshalXml(xsdPath, source, Orders.class);
                    if (orderObj instanceof Orders) {
                        Orders order = (Orders) orderObj;
                        OrderType orderType = null;
                        for (OrderType r : order.getOrder()) {
                            if (String.valueOf(r.getId().intValue()).equals(orderid)) {
                                orderType = r;
                            }
                        }
                        if (DBEntities.saveOrder(orderType)) {
                            XmlUtils.marshalXml(order, filePath);
                            Map<String, Object> params = new LinkedHashMap<String, Object>();
                            params.put("userpath", webPath + "WEB-INF/XmlDoc/Users.xml");
                            params.put("userdetailpath", webPath + "WEB-INF/XmlDoc/UserDetails.xml");
                            params.put("type", "inorder");
                            String responseString = XmlUtils.transformToString(xslPath, source, params);
                            out.write(responseString);
                        }

                    }
                }

            }
        } finally {
            out.close();
        }
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SAXException ex) {
            Logger.getLogger(OrderController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(OrderController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (SAXException ex) {
            Logger.getLogger(OrderController.class.getName()).log(Level.SEVERE, null, ex);
        } catch (SQLException ex) {
            Logger.getLogger(OrderController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
